/**
 * 实现并发限制的异步调度器
 * 同时保证运行的任务最多有2个
 */

class Scheduler {
  constructor() {
    // 用于存储任务的队列
    this.taskQueue = [];
    // 当前正在执行的任务数量
    this.runningTaskCount = 0;
    // 最大并发数
    this.maxTaskCount = 2;
  }

  /**
   * 添加任务函数
   */
  addTask(task) {
    return new Promise(resolve => {
      task.resolve = resolve;
      if (this.runningTaskCount < this.maxTaskCount) {
        this.runTask(task);
      } else {
        this.taskQueue.push(task);
      }
    });
  }

  /**
   * 执行异步任务
   */
  runTask(task) {
    this.runningTaskCount++;
    task().then(() => {
      task.resolve();
      this.runningTaskCount--;
      if (this.taskQueue.length > 0) {
        this.runTask(this.taskQueue.shift());
      }
    });
  }
}

// 测试
const scheduler = new Scheduler();
const timeout = time => new Promise(resolve => setTimeout(resolve, time));
const addPromiseTask = (time, order) => scheduler.addTask(() => timeout(time).then(() => console.log(order)));

addPromiseTask(1000, "1");
addPromiseTask(500, "2");
addPromiseTask(300, "3");
addPromiseTask(400, "4");
